<template>
  <div class="table-box">
    <div class="tools" v-if="toolsConfig">
      <div class="tools__opt">
        <!-- 字段选择 -->
        <el-popover v-if="toolsConfig.includes('dynamicColumn')" placement="bottom" width="100" trigger="click">
          <el-checkbox-group
            class="checkbox-table-col"
            v-model="checkedTableCol"
            style="padding: 10px; padding-top: 0px"
          >
            <el-checkbox
              style="display: inline-block; margin-top: 15px"
              v-for="item in fieldSetting"
              :label="item.prop"
              :disabled="item.disabled"
              :key="item.prop"
            >
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
          <el-button type="text" style="color: #333" slot="reference" icon="el-icon-setting">字段设置</el-button>
        </el-popover>
        <!-- 筛选 -->
        <filterCondition
          ref="filterConditionRef"
          @filter-confirm="filterConfirm"
          :options="$attrs.filterCol"
        ></filterCondition>
        <!-- 中间位置 -->
        <slot name="center"></slot>
      </div>
      <div class="tools__search" v-if="toolsConfig.includes('search')">
        <div class="header-slot">
          <slot></slot>
        </div>
        <!-- <span>Filter:</span> -->
        <el-input v-model="searVal" @change="searChange" :placeholder="filterPlaceholder">
          <i slot="suffix" class="el-icon-search"></i>
        </el-input>
      </div>
    </div>
    <el-table
      ref="secTable"
      style="width: 100%"
      :data="tableData"
      :header-cell-style="{
        background: '#fafafa',
        color: '#333',
        borderBottom: '1px solid #f0f0f0',
      }"
      v-bind="$attrs"
      v-on="$listeners"
    >
      <el-table-column v-if="selection" type="selection" width="55" align="center"></el-table-column>

      <!-- 文本数据渲染 -->
      <template v-for="(item, index) in tableCol || []">
        <el-table-column
          v-if="
            (slotType.includes(item.type) || slotType.includes(colType[item.prop])) &&
            checkedTableCol.indexOf(item.prop) != -1
          "
          :prop="item.prop"
          :label="item.label"
          :fixed="item.fixed"
          :column-key="item.columnKey"
          :render-header="item.renderHeader"
          :sort-method="item.sortMethod"
          :sort-by="item.sortBy"
          :sort-orders="item.sortOrders"
          :header-align="item.headerAlign"
          :class-name="item.className"
          :label-class-name="item.labelClassName"
          :selectable="item.selectable"
          :reserve-selection="item.reserveSelection"
          :filters="item.filters"
          :filter-placement="item.filterPlacement"
          :filter-method="item.filterMethod"
          :ffilter-multiple="item.filterMultiple"
          :filtered-value="item.filteredValue"
          :key="item.prop"
          :width="item.width"
          :min-width="item.minWidth"
          :align="item.align || align"
          :sortable="item.sortable"
          :resizable="item.resizable"
          :formatter="item.formatter"
          :show-overflow-tooltip="item.showOverflowTooltip"
        >
          <template slot-scope="scope">
            <!-- input输入框组件 type是text/textarea 走这里-->
            <el-input
              v-if="inputType.includes(item.type) || inputType.includes(colType[item.prop])"
              :show-word-limit="item.showWrodLimit"
              :type="item.type || colType[item.prop]"
              :maxlength="item.maxlength || 150"
              :minlength="item.minlength"
              :clearable="item.clearable || true"
              :show-password="item.showPassword"
              :prefix-icon="item.prefixicon"
              :suffix-icon="item.suffixIcon"
              :rows="item.rows"
              :autosize="item.autosize"
              :autocomplete="item.autocomplete"
              :name="item.name"
              :max="item.max"
              :min="item.min"
              :step="item.step"
              :resize="item.resize"
              :autofocus="item.autofocus"
              :form="item.form"
              :tabindex="item.tabindex"
              :validate-event="item.validateEvent"
              :disabled="item.disabled || disabledProp[item.prop] || scope.row.disabled || false"
              :placeholder="item.placeholder || `请输入`"
              v-model="scope.row[item.prop]"
              @focus="item.focus && item.focus($event)"
              @blur="item.blur && item.blur($event)"
              @clear="item.clear && item.clear($event)"
              @change="item.change && item.change($event)"
              @input="item.input && item.input($event)"
            ></el-input>
            <!-- select选择器组件 type是select/option 走这里-->
            <el-select
              v-else-if="selectType.includes(item.type) || selectType.includes(colType[item.prop])"
              v-model="scope.row[item.prop]"
              default-first-option
              :clearable="item.clearable || true"
              :disabled="item.disabled || disabledProp[item.prop] || scope.row.disabled || false"
              :remote="item.remote"
              :allow-create="item.allowCreate"
              :multiple="item.multiple"
              :filterable="item.filterable"
              @visible-change="item.visibleChange && item.visibleChange($event)"
              @remove-tag="item.removeTag && item.removeTag($event)"
              @clear="item.clear && item.clear($event)"
              @blur="item.blur && item.blur($event)"
              @focus="item.focus && item.focus($event)"
              @change="item.change && item.change($event, scope)"
              :remote-method="
                item.remoteMethod ||
                ((query) => {
                  remoteMethod(query, item.prop);
                })
              "
              :placeholder="item.placeholder || `请选择`"
            >
              <el-option
                v-for="(oItem, okey) in item.option || item.options || item.optionData || optionData[item.prop] || []"
                :key="okey"
                :label="(item.optionProps && oItem[item.optionProps.label]) || oItem.label"
                :value="(item.optionProps && oItem[item.optionProps.value]) || oItem.value"
              >
              </el-option>
            </el-select>
            <!-- el-link 组件 target（a标签原生属性target）-->
            <template v-else-if="item.type === 'link'">
              <el-link
                :type="item.linkConfig.type || 'primary'"
                :underline="item.linkConfig.underline"
                :disabled="item.linkConfig.disabled"
                :href="item.linkConfig.href"
                :icon="item.linkConfig.icon"
                :target="item.linkConfig.target"
                @click="item.linkConfig.click && item.linkConfig.click(scope)"
                >{{ scope.row[item.prop] }}</el-link
              >
            </template>
            <!-- 为了实现进度和状态 有一个状态点标识-->
            <template v-else-if="item.type === 'status'">
              <span class="ant-badge ant-badge-status"
                ><span
                  :class="`ant-badge-status-dot ant-badge-status-${
                    (item.statusClass && item.statusClass(scope)) || 'pending'
                  }`"
                ></span
                ><span class="ant-badge-status-text">{{
                  (item.formatter && item.formatter(scope)) || scope.row[item.prop]
                }}</span></span
              >
            </template>
            <!-- 插槽 type是slot 走这里-->
            <slot v-else :name="item.slotName || item.prop" :data="scope" />
          </template>
          <!-- <template v-slot="scope" v-else>
            <slot :name="item.slotName || item.field || item.prop" :data="scope" />
          </template> -->
        </el-table-column>
        <!-- 操作 type是operation 走这里-->
        <el-table-column
          :width="item.width"
          :label="item.label"
          :min-width="item.minWidth"
          :fixed="item.fixed || 'right'"
          :align="item.align || align"
          :render-header="item.renderHeader"
          v-else-if="item.type === 'operation'"
          :key="index"
        >
          <template v-slot="scope">
            <span v-for="(child, cIndex) in item.children" :key="cIndex">
              <el-tooltip
                v-if="child.tooltip"
                :effect="child.tooltip.effect"
                :content="child.tooltip.content"
                :placement="child.tooltip.placement || 'top'"
              >
                <el-button
                  style="margin-right: 5px"
                  :icon="child.icon"
                  :type="child.type || 'text'"
                  :loading="scope.row.loading && loadingProp[child.prop]"
                  v-show="!(child.hide && child.hide(scope))"
                  :disabled="
                    (child.disabled && (typeof child.disabled == 'boolean' ? child.disabled : child.disabled(scope))) ||
                    item.disabled ||
                    (item.disabledIndex && item.disabledIndex.includes(scope.$index))
                  "
                  :circle="child.circle || item.circle"
                  :round="child.round || item.round"
                  :plain="child.plain || item.plain"
                  @click="child.click && child.click(scope)"
                >
                  {{
                    typeof child.title == "function"
                      ? child.title(scope)
                      : child.title || typeof child.label == "function"
                      ? child.label(scope)
                      : child.label
                  }}</el-button
                >
              </el-tooltip>
              <el-button
                v-else
                style="margin-right: 5px"
                :icon="child.icon"
                :type="child.type || 'text'"
                :loading="scope.row.loading && loadingProp[child.prop]"
                v-show="!(child.hide && child.hide(scope))"
                :disabled="
                  (child.disabled && (typeof child.disabled == 'boolean' ? child.disabled : child.disabled(scope))) ||
                  item.disabled ||
                  (item.disabledIndex && item.disabledIndex.includes(scope.$index))
                "
                :circle="child.circle || item.circle"
                :round="child.round || item.round"
                :plain="child.plain || item.plain"
                @click="child.click && child.click(scope)"
              >
                {{
                  typeof child.title == "function"
                    ? child.title(scope)
                    : child.title || typeof child.label == "function"
                    ? child.label(scope)
                    : child.label
                }}</el-button
              ></span
            >
          </template>
        </el-table-column>
        <!-- 默认情况 -->
        <!-- :fixed="item.fixed || 'right'" -->
        <el-table-column
          v-else-if="checkedTableCol.indexOf(item.prop) != -1"
          :prop="item.prop"
          :label="item.label"
          :column-key="item.columnKey"
          :render-header="item.renderHeader"
          :sort-method="item.sortMethod"
          :sort-by="item.sortBy"
          :sort-orders="item.sortOrders"
          :header-align="item.headerAlign"
          :class-name="item.className"
          :label-class-name="item.labelClassName"
          :selectable="item.selectable"
          :reserve-selection="item.reserveSelection"
          :filters="item.filters"
          :filter-placement="item.filterPlacement"
          :filter-method="item.filterMethod"
          :filter-multiple="item.filterMultiple"
          :filtered-value="item.filteredValue"
          :key="item.prop"
          :width="item.width"
          :min-width="item.minWidth"
          :align="item.align || align"
          :sortable="item.sortable"
          :resizable="item.resizable"
          :formatter="item.formatter"
          :show-overflow-tooltip="item.showOverflowTooltip"
        >
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>

<script>
import filterCondition from "./filterCondition";
export default {
  name: "secExtTable",
  components: { filterCondition },
  props: {
    selection: Boolean,
    loadingProp: {
      type: Object,
      default: () => {},
    },
    checkedCol: {
      type: Array,
      default: () => [],
    },
    toolsConfig: {
      type: String,
      default: "search,dynamicColumn",
    },
    optionData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    disabledProp: {
      //让哪个form表单disabled 例如  disabledProp:{name:true} 让字段为name的表单失效
      type: Object,
      default: () => {
        return {};
      },
    },
    // 行的类型
    colType: {
      type: Object,
      default: () => {
        return {};
      },
    },
    tableData: Array,
    tableCol: Array,
    tableHead: Array,
    align: {
      type: String,
      default: "left",
    },
  },
  data() {
    return {
      checkedTableCol: [],
      searVal: "",
      slotType: ["slot", "select", "option", "text", "textarea", "link", "cascader", "status"],
      selectType: ["select", "option"],
      inputType: ["text", "textarea"],
    };
  },
  mounted() {},
  methods: {
    //用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
    toggleRowSelection(row, selected) {
      this.$refs.secTable.toggleRowSelection(row, selected);
    },
    //用于多选表格，清空用户的选择
    clearSelection() {
      this.$refs.secTable.clearSelection();
    },
    filterConfirm(data) {
      this.$emit("filter-confirm", data);
    },
    searChange() {
      this.$emit("search-change", this.searVal);
    },
    reset() {
      this.searVal = "";
      // this.checkedTableCol = [];
      this.$refs.filterConditionRef.clear();
    },
  },
  computed: {
    fieldSetting() {
      return this.tableCol.filter((item) => item.label !== "操作");
    },
    filterPlaceholder() {
      let filterCol = this.tableCol.filter((item) => item.searchPlaceholder === "1");
      return filterCol.map((item) => item.label)?.join("/") || "请输入";
      // return `支持筛选的列 ${label}`;
    },
  },
  watch: {
    checkedTableCol: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal.length === 1) {
          this.fieldSetting.forEach((item) => {
            if (newVal.includes(item.prop)) {
              item["disabled"] = true;
            }
          });
        } else {
          this.fieldSetting.forEach((item) => {
            item["disabled"] = false;
          });
        }
      },
    },
    tableCol: {
      deep: true,
      immediate: true,
      handler(newVal) {
        this.checkedTableCol = [];
        newVal.forEach((item) => {
          //list:1 字段设置 默认选中的列
          if (item.list === "1") {
            this.checkedTableCol.push(item.prop);
          }
        });
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.checkbox-table-col {
  ::v-deep .el-checkbox__input {
    float: left;
    line-height: 22px;
  }
  ::v-deep .el-checkbox__label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 120px;
  }
}
.table-col__show {
  .table-col__item {
    line-height: 35px;
    cursor: pointer;
    // text-align: center;
    margin-bottom: 5px;
    &:hover {
      color: #00bdac;
    }
    &.active {
      color: #00bdac;
      // background: #f5f7fa;
    }
    i {
      font-weight: 600;
      margin-right: 20px;
      color: #00bdac;
    }
  }
}
.ant-badge-dot {
  width: 6px;
  height: 6px;
  background: #f5222d;
  border-radius: 100%;
  -webkit-box-shadow: 0 0 0 1px #fff;
  box-shadow: 0 0 0 1px #fff;
}
.ant-badge-status-dot {
  position: relative;
  top: -1px;
  display: inline-block;
  width: 6px;
  height: 6px;
  vertical-align: middle;
  border-radius: 50%;
}

.ant-badge-status-success,
.ant-badge-status-over {
  background-color: #52c41a;
}
.ant-badge-status-pending {
  position: relative;
  background-color: #1890ff;
}
.ant-badge-status-default,
.ant-badge-status-close {
  background-color: #d9d9d9;
}
.ant-badge-status-error {
  background-color: #f5222d;
}
.ant-badge-status-warning {
  background-color: #faad14;
}
.ant-badge-status-pending:after {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  height: 100%;
  border: 1px solid #1890ff;
  border-radius: 50%;
  -webkit-animation: antStatusProcessing 1.2s ease-in-out infinite;
  animation: antStatusProcessing 1.2s ease-in-out infinite;
  content: "";
}

@keyframes antStatusProcessing {
  0% {
    -webkit-transform: scale(0.8);
    transform: scale(0.8);
    opacity: 0.5;
  }

  to {
    -webkit-transform: scale(2.4);
    transform: scale(2.4);
    opacity: 0;
  }
}
.ant-badge-status-text {
  margin-left: 5px;
}
.tools {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  .tools__search {
    display: flex;
    .header-slot {
      margin-right: 20px;
    }
    span {
      margin-right: 10px;
    }
    .el-input {
      width: 250px;
    }
  }
}
.el-icon-search {
  margin: 10px 5px 0 0;
}
</style>
